import React, { Component } from 'react'

import { Modal, Form, Input, Button, Table, Cascader } from 'antd';
import { connect } from 'dva';

import { ColumnProps, RowSelectionType } from 'antd/es/table';

import { FormComponentProps } from "antd/lib/form/Form";
import { SearchCol, SearchRow } from '@/styled/form';

interface Owner {
  name: string;
  areaName: string;
}

interface IProps extends FormComponentProps {
  dispatch?: Function,
  history?: any,
  visible: boolean,
  cancelProperty: Function,
  setProperty: Function,
  list?: {
    data: Array<any>,
    dataCnt: number | string
  },
  loading?: boolean;
  provice?: Array<any>;
  sub?: Array<any>;
}

const FormItem = Form.Item;
const ONE_PAGE_SIZE = 5;

@connect(({ owner, loading, location }) => ({
  list: owner.propertyList,
  loading: loading.effects['owner/queryPropertyPage'],
  provice: location.provice,
  sub: location.sub
}))
class PropertyModalForm extends Component<IProps, any> {

  state = {
    option: [],
    selectedRows: [],
    selectedRowKeys: null,
    areaName: '',
    areaList: [],
  }

  handleCancel = () => {
    this.props.cancelProperty()
  }

  handleOk = () => {
    this.props.setProperty(this.state.selectedRows[0])
  }

  queryData(params = {}, pageNum = 0, pageSize = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;
    dispatch({
      type: 'owner/queryPropertyPage',
      payload: {
        ...params,
        pageNum,
        pageSize
      }
    })
    this.setState({
      selectedRows: [],
      selectedRowKeys: null,
    })
  }

  search = e => {
    e.preventDefault();
    const { areaList } = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.queryData({
          name: values.name,
          areaId: Array.isArray(areaList) && areaList.length > 0 ? areaList[areaList.length-1] : null
        })
      }
    });
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'location/queryList' }).then(() => {
      this.setState({ option: this.props.provice })
    });
    this.queryData()
  }

  onSelectChange = (selectedRowKeys: any, selectedRows: any) => {
    this.setState({ selectedRowKeys, selectedRows });
  }

  loadData = (selectedOptions) => {
    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    if (+targetOption.value < 1e8) {
      dispatch({ type: 'location/querySubordinate', payload: targetOption.value }).then(() => {
        targetOption.loading = false;
        targetOption.children = this.props.sub;
        this.setState({
          option: [...this.state.option],
        });
      })
    }
  };

  onChangeCascader = (value) => {
    this.setState({
      areaList: value
    })
  };

  render() {
    const { visible, list, form } = this.props;
    const { getFieldDecorator } = form;
    const { data = [], dataCnt } = list;

    const type: RowSelectionType = 'radio';

    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };

    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
      type
    };

    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      id: item.id,
      name: item.name,
      areaName: item.areaName,
    })
    ) : []
    const pagination = {
      total: +dataCnt,
      showTotal: total => `共 ${+total} 条`,
      showQuickJumper: true,
      pageSize: ONE_PAGE_SIZE,
      size: "small",
      onChange: (current) => {
        this.setState({ current })
        this.props.form.validateFields((err, values) => {
          if (!err) {
            this.queryData(values.name, current)
          }
        });
      },
    };
    const columns: ColumnProps<Owner>[] = [{
      title: '所属区域',
      dataIndex: 'areaName',
    }, {
      title: '物业单位名称',
      dataIndex: 'name',
    }];

    return (
      <Modal
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width={900}
        title="选择物业"
      >
        <Form layout="inline" onSubmit={this.search} style={{ height: '50px' }}>
          <SearchCol key={2} span={9}>
            <FormItem
              label="所属区域"
              {...formItemLayout}
            >
              {getFieldDecorator('areaId', {
                rules: [{ message: '所属区域' }],
              })(
                <div>
                  <Cascader
                    options={this.state.option || this.props.provice}
                    loadData={this.loadData}
                    changeOnSelect
                    placeholder={this.state.areaName || '请选择'}
                    onChange={this.onChangeCascader}
                  />
                </div>
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={1} span={9}>
            <FormItem label="物业单位名称" {...formItemLayout}>
              {getFieldDecorator('name', {
                rules: [{ message: '输入单位名称' }],
              })(
                <Input placeholder="单位名称" />
              )}
            </FormItem>
          </SearchCol>
          <SearchCol span={6} key={9}>
            <SearchRow type="flex" justify="end">
              <Button style={{ margin: '5px 15px 0 0' }} onClick={() => {
                this.props.form.resetFields();
                this.setState({ option: [], areaList: [] })
              }} value="small">重 置</Button>
              <Button style={{ margin: '5px 0 0 0' }} htmlType="submit" type="primary" value="small">搜 索</Button>
            </SearchRow>
          </SearchCol>
        </Form>
        <Table
          columns={columns}
          rowSelection={rowSelection}
          pagination={pagination}
          dataSource={ans}
          bordered
          okText="确认"
          cancelText="取消"
          loading={this.props.loading}
        />
      </Modal>
    )
  }
}

const PropertyModal = Form.create<IProps>()(PropertyModalForm);
export default PropertyModal;
